import 'package:flutter/material.dart';
import '../tools/tcp_connection_service.dart';

class TcpConnectionExample extends StatefulWidget {
  @override
  _TcpConnectionExampleState createState() => _TcpConnectionExampleState();
}

class _TcpConnectionExampleState extends State<TcpConnectionExample> {
  late TcpConnectionService _tcpService;
  String _connectionStatus = '未连接';
  final TextEditingController _hostController = TextEditingController(text: 'localhost');
  final TextEditingController _portController = TextEditingController(text: '8080');
  final TextEditingController _messageController = TextEditingController(text: 'Hello TCP');
  String _log = '';

  @override
  void initState() {
    super.initState();
    _initializeTcpService();
  }

  void _initializeTcpService() {
    _tcpService = TcpConnectionService(
      host: _hostController.text,
      port: int.tryParse(_portController.text) ?? 8080,
    );

    // 监听连接状态变化
    _tcpService.connectionStateStream.listen((state) {
      setState(() {
        switch (state) {
          case DeviceConnectionState.disconnected:
            _connectionStatus = '已断开';
            break;
          case DeviceConnectionState.connecting:
            _connectionStatus = '连接中...';
            break;
          case DeviceConnectionState.connected:
            _connectionStatus = '已连接';
            break;
        }
        _addLog('状态变化: $_connectionStatus');
      });
    });

    // 监听错误
    _tcpService.errorStream.listen((error) {
      setState(() {
        _addLog('错误: $error');
      });
    });

    // 监听接收的数据
    _tcpService.dataStream.listen((data) {
      setState(() {
        _addLog('收到数据: ${String.fromCharCodes(data)}');
      });
    });
  }

  void _addLog(String message) {
    final timestamp = DateTime.now().toString().split(' ')[1];
    _log = '[$timestamp] $message\n$_log';
    if (_log.length > 1000) {
      _log = _log.substring(0, 1000);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('TCP 连接示例'),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Text('连接状态: $_connectionStatus', style: TextStyle(fontSize: 18)),
            SizedBox(height: 16),
            TextField(
              controller: _hostController,
              decoration: InputDecoration(labelText: '主机地址'),
            ),
            TextField(
              controller: _portController,
              decoration: InputDecoration(labelText: '端口'),
              keyboardType: TextInputType.number,
            ),
            SizedBox(height: 16),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(
                  onPressed: () {
                    _tcpService.dispose();
                    _initializeTcpService();
                    _tcpService.connect();
                  },
                  child: Text('连接'),
                ),
                ElevatedButton(
                  onPressed: () => _tcpService.disconnect(),
                  child: Text('断开'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.red,
                  ),
                ),
              ],
            ),
            SizedBox(height: 16),
            TextField(
              controller: _messageController,
              decoration: InputDecoration(labelText: '发送消息'),
            ),
            ElevatedButton(
              onPressed: () {
                final message = _messageController.text;
                if (message.isNotEmpty) {
                  _tcpService.sendData(message.codeUnits);
                  _addLog('发送数据: $message');
                }
              },
              child: Text('发送'),
            ),
            SizedBox(height: 16),
            Expanded(
              child: Container(
                decoration: BoxDecoration(
                  border: Border.all(),
                  borderRadius: BorderRadius.circular(4),
                ),
                padding: EdgeInsets.all(8),
                child: SingleChildScrollView(
                  child: Text(_log),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _tcpService.dispose();
    _hostController.dispose();
    _portController.dispose();
    _messageController.dispose();
    super.dispose();
  }
}